// Use serde for serialization/deserialization
use serde::Deserialize;
use std::fs;
use base64::prelude::*;

// 数据库类型枚举
#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum DatabaseType {
    #[serde(rename = "mongo")]
    Mongo,
    #[serde(rename = "postgresql")]
    PostgreSQL,
}

// Define configuration structure, corresponding to yaml file structure
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
    pub worker_id: u32,
    pub kernel_num: u32,
    pub log_level: String,
    pub allowed_hosts: String,
    pub access_expire: u32,
    pub bucket: String,
    pub keep_timeout: u32,
    pub keep_alive_interval: u32,
    pub urls: String,
    pub ffmpeg_path: String,
    pub executor_timeout: u32,
    pub kernel_addr: String,
    pub connection_string: String,
    pub kernel_auth: String,
    pub connection_key: Option<String>,
    pub db_type: DatabaseType,
}

impl Config {
    pub fn load() -> Result<Self, anyhow::Error> {
        // Read configuration file
        let config_content = fs::read_to_string("config.yaml")?;
        // Parse yaml content
        let config: Config = serde_yaml::from_str(&config_content)?;
        Ok(config)
    }

    pub fn db_connection_string(&self) -> String {
        Self::parse_connection_string(&self.connection_string)
    }
    
    pub fn db_type(&self) -> DatabaseType {
        self.db_type
    }

    fn parse_connection_string(connection_string: &str) -> String {
        println!("Raw connection string: {}", connection_string);
        
        // Match C# logic: strip first 5 characters, then decode base64
        if connection_string.len() > 5 {
            let stripped = &connection_string[5..];
            println!("Stripped prefix (5 chars): {}", stripped);
            if let Ok(decoded) = base64::prelude::BASE64_STANDARD.decode(stripped) {
                println!("Decoded bytes: {:?}", decoded);
                if let Ok(result) = String::from_utf8(decoded) {
                    println!("Final result: {}", result);
                    return result;
                }
            }
        }
        
        // If base64 decoding fails, try to use the string directly
        println!("Using connection string directly: {}", connection_string);
        connection_string.to_string()
    }
}